package leetcode.n2022;


import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

import java.util.List;

/**
 * https://leetcode-cn.com/problems/add-two-numbers/
 *
 * @program: brushing
 * @description:
 * @author: LiuQiang
 * @create: 2022-01-03
 **/
public class AddTwoNumbers {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode listNode = new ListNode(0);
        ListNode result = listNode;
        int sum = 0;
        int n = 0;

        while (l1 != null || l2 != null || n > 0) {
            int val1 = 0;
            int val2 = 0;

            if (l1 != null) {
                val1 = l1.val;
            }
            if (l2 != null) {
                val2 = l2.val;
            }

            sum = val1 + val2 + n;
            listNode.val = sum %10;
            if (sum > 9) {
                n = 1;
            } else {
                n = 0;
            }

            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }

            if (l1 != null || l2 != null || n > 0) {
                listNode.next = new ListNode(0);
                listNode = listNode.next;
            }
        }



        return result;
    }


    public static void main(String[] args) {
        Log log = LogFactory.get();

        AddTwoNumbers result = new AddTwoNumbers();

        ListNode l1 = new ListNode(9);
        ListNode a1 = new ListNode(9);
        l1.next = a1;
        ListNode a2 = new ListNode(9);
        a1.next = a2;
        ListNode a3 = new ListNode(9);
        a2.next = a3;
        ListNode a4 = new ListNode(9);
        a3.next = a4;
        ListNode a5 = new ListNode(9);
        a4.next = a5;
        ListNode a6 = new ListNode(9);
        a5.next = a6;

        ListNode l2 = new ListNode(9);
        ListNode b1 = new ListNode(9);
        l2.next = b1;
        ListNode b2 = new ListNode(9);
        b1.next = b2;
        ListNode b3 = new ListNode(9);
        b2.next = b3;


        ListNode r = result.addTwoNumbers(l1,l2);

        while (r != null) {
            System.out.printf(String.valueOf(r.val));
            r = r.next;
        }

    }
}
